package 动态规划;

import java.util.Arrays;

public class 下降路径最小和 {

    public int minFallingPathSum(int[][] matrix) {
         int m = matrix.length;
         int n = matrix[0].length;
        int[][] dp = new int[m][n + 2];
        for (int i = 1; i < n+1; i++) {
            dp[0][i] = matrix[0][i-1];
        }
        for (int i = 0; i < m; i++) {
            dp[i][0] = Integer.MAX_VALUE;
            dp[i][n+1] = Integer.MAX_VALUE;
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n+1; j++) {
                dp[i][j] = Math.min(dp[i-1][j-1],Math.min(dp[i-1][j],dp[i-1][j+1]))+matrix[i][j-1];
                System.out.print(dp[i][j]+" ");
            }
        }
        return Arrays.stream(dp[m-1]).min().getAsInt();
    }
}
